package com.mt.api.modules.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.mt.common.response.WebResponse;
import com.mt.common.response.WebResponseUtils;
import com.mt.api.modules.domain.AppBoss;
import com.mt.api.modules.domain.WxUserInfo;
import com.mt.api.modules.domain.dto.JwtUserDto;
import com.mt.api.modules.manager.IBossManager;
import com.mt.api.modules.mapper.AppBossMapper;
import com.mt.api.modules.service.AppWeixinService;
import com.mt.api.util.JwtUserUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @Author: plover
 * @Date: 2020/07/06/4:15 下午
 * @Description:
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AppWeixinServiceImpl implements AppWeixinService {

    private final AppBossMapper bossMapper;
    private final IBossManager bossManager;

    private final WxMaService wxMaService;

    @Override
    public WebResponse login(String code) {
        JwtUserDto jwtUser = JwtUserUtils.getJwtUser();
        if (Objects.isNull(jwtUser)) {
            return WebResponseUtils.success();
        }
        Integer id = JwtUserUtils.getJwtUser().getAppBoss().getId();
        AppBoss boss = bossManager.getById(id);
        if (Objects.isNull(boss)) {
            return WebResponseUtils.error("账号不存在");
        }
        try {
            WxMaJscode2SessionResult jscode2SessionResult = wxMaService.getUserService().getSessionInfo(code);
            if (Objects.nonNull(jscode2SessionResult)) {
                String openid = jscode2SessionResult.getOpenid();
                String unionid = jscode2SessionResult.getUnionid();
                String session_key = jscode2SessionResult.getSessionKey();

                Date now = new Date();
                boss.setOpenId(openid);
                boss.setUnionId(unionid);
                boss.setLastLoginTime(now);
                boss.setSessionKey(session_key);
                bossMapper.updateById(boss);
                return WebResponseUtils.success();
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return WebResponseUtils.error("微信登录失败");
    }

    @Override
    public WebResponse bindUserInfo(WxUserInfo wxUserInfo) {
        Integer id = JwtUserUtils.getJwtUser().getAppBoss().getId();
        AppBoss boss = bossManager.getById(id);
        AppBoss opBoss = new AppBoss();
        opBoss.setId(boss.getId());
        opBoss.setNickName(wxUserInfo.getNickName());
        opBoss.setAvatarUrl(wxUserInfo.getAvatarUrl());
        bossMapper.updateById(opBoss);
        return WebResponseUtils.success();
    }

}
